/**
 * 
 */
package com.ruyipu.forum.activity;

import java.util.List;

import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

import com.ruyipu.forum.R;
import com.ruyipu.forum.adapter.DiscussionAdapter;
import com.ruyipu.forum.base.Factory;
import com.ruyipu.forum.base.GlobalUtil;
import com.ruyipu.forum.base.Header;
import com.ruyipu.forum.interfaces.IItem;
import com.ruyipu.forum.item.Category;
import com.ruyipu.forum.item.Discussion;
import com.ruyipu.forum.model.DiscussionModel;

/**
 * @author donald
 * 
 */
public class CategoryActivity extends BaseActivity {

	public static final String TAG = CategoryActivity.class.getSimpleName();
	public static final String NAME = CategoryActivity.class.getName();

	private DiscussionAdapter myAdapter;
	private Category category;
	private int iCategoryId;

	private ListView lvCategory;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.category);

		Intent intent = getIntent();
		category = (Category) intent.getSerializableExtra(Category.TAG);

		if (null != category) {
			iCategoryId = category.getId();
		} else {
			GlobalUtil.showShortToast(this, "No data");
			finish();
			return;
		}

		super.onCreate(savedInstanceState);
		refresh(null);
	}

	@Override
	protected void makeWidget() {
		myHeader = new Header(this, category.getName());

		lvCategory = (ListView) findViewById(R.id.lvCategory);
	}

	@Override
	protected void initWidget() {
		lvCategory.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				GlobalUtil.viewDiscussion(CategoryActivity.this, (Discussion) dataList.get(arg2));
			}
		});
	}

	@Override
	public void refresh(View v) {
		super.refresh(v);
		new MyDownloader().execute("");
	}

	private class MyDownloader extends AsyncDownloader {

		@Override
		protected JSONObject doInBackground(Object... params) {
			return DiscussionModel.getInstance().getDiscussionOfCategory(
					CategoryActivity.this, iCategoryId, 20, 1);
		}
	}

	@Override
	protected void updateData(JSONObject jsonObject) {
		if (null == jsonObject) {
			return;
		}
		List<IItem> tempList = Factory.factoryItemList(jsonObject,
				Discussion.NAME);
		if (!tempList.isEmpty()) {
			if (dataList.isEmpty()) {
				dataList.addAll(tempList);
				myAdapter = new DiscussionAdapter(CategoryActivity.this,
						dataList);
				lvCategory.setAdapter(myAdapter);
				lvCategory.setLayoutAnimation(lacList);
			} else {
				// TODO Update data
				myAdapter.notifyDataSetChanged();
			}
		}
	}

	@Override
	protected void loadLocalData() {
		JSONObject jsonObject = DiscussionModel.getInstance()
				.loadLocalDiscussionOfCategory(iCategoryId, 20, 1);
		updateData(jsonObject);
	}
}
